<template>
  <div :id="mapElId" class="map">
    <div ref="winElId" style="display:none;">
      <slot/>  
    </div>
  </div>
</template>

<script lang="ts">
import Vue from "vue";
import { sysUuid } from "tscommon/ts/ext";
import Global from "system.global";
import {LoadJS,whichElement,dataset} from 'tscommon/ts/dom.ext';
let loaded = false;


export default Vue.extend({
  data() {
    return {
      mapElId: sysUuid(),
      map:null as null|AMapClass,
      cluster:null as null|MarkerClusterer,
      drawMarkers:[] as AMapMarker[],
      infoWindow:null as AMapInfoWindow|null
    };
  },
  mounted() {
    if (!loaded) {
      const g: any = Global();
      g.onApiLoaded = () => {
        this.initMap();
        delete g.onApiLoaded;
      };
      LoadJS(
        "AMapEl",
        `https://webapi.amap.com/maps?v=1.4.10&key=${
          g.AMapKey
        }&callback=onApiLoaded`
      );
      loaded=true;
    } else {
      this.initMap();
    }
  },
  props:{
    zoom:{
      type:Number,
      default:14
    },
    center:<any>{
      type:Array,
      default(){
        return [113.55027,22.271249]
      }
    },
    markers:{
      type:Array
    },
    showWin:{
      type:Number
    },
    winLng:{
      type:Number
    },
    winLat:{
      type:Number
    },
    offset:<any>{
      type:Array,
      default(){
        return [0,0]
      }
    },
    markOffset:<any>{
      type:Array,
      default(){
        return [0,0]
      }
    },
    cluserMarker:{
      type:Function
    },
    mapStyle:{
      type:String,
      default:"normal"
    }
  },
  methods: {
    click(mark:any){
      this.$emit('mark-click',mark);
    },
    initMap() {
      this.map=new AMap.Map(this.mapElId, {
        zoom: this.zoom,
        center:this.center,
        mapStyle: 'amap://styles/'+this.mapStyle
      });
      this.renderMarker();
      this.$emit('inited',this.map);
    },
    renderMarker(){
      if(this.map==null||this.markers==null||this.markers.length==0)return;
      const map = this.map;
      const markers:AMapMarker[] = [];
      let tmpMarker:AMapMarker;
      (<any>this.markers).forEach((m:{lng:number,lat:number})=>{
        tmpMarker = new AMap.Marker({
          position:new AMap.LngLat(m.lng,m.lat),
          content:this.cluserMarker?this.cluserMarker({cfg:m}):null,
          extData:m,
          offset:new AMap.Pixel((<number[]>this.markOffset)[0],(<number[]>this.markOffset)[1])
        });
        tmpMarker.on('click',()=>{
          this.click(m);
        });
        markers.push(tmpMarker);
      })
      if(this.cluster!=null){
        this.cluster.setMarkers(markers);
      }else{
        // console.log(this.cluserMarker)
        map.plugin(["AMap.MarkerClusterer"],()=>{
          const p:any = {averageCenter:true,gridSize:10};
          this.cluserMarker&&(p.renderCluserMarker=this.cluserMarker);
          this.cluster = new AMap.MarkerClusterer(map,markers,p);
          this.cluster.on('click',({markers,map}:{markers:AMapMarker[],map:AMapClass})=>{
            if(map.getZoom()==18){
              //TODO:经纬度重叠
              console.log(markers);
            }
          })
        });
      }
      this.drawMarkers = markers;
    },
    bindclick(){
      const dom:any = (<any>this.infoWindow).getContentDom();
      if(dom==null){
        setTimeout(()=>{
          this.bindclick();
        },200)
      }else{
        dom.onclick = (e:any)=>{
          const name = whichElement(e).getAttribute('name');
          if(name!=null){
            this.$emit('win-click',name);
          }
        }
      }
    }
  },
  watch:{
    markers(){
      this.renderMarker();
    },
    showWin(){
      if(this.showWin==null||this.map==null)return;
      if(this.showWin<0&&this.infoWindow==null)return;//关闭
      if(this.showWin<0&&this.infoWindow!=null){
        this.infoWindow.close();
        this.infoWindow=null;
        return;
      }//关闭

      const info:any = this.$refs.winElId;
        const d = dataset(info.children[0]);
      if(this.infoWindow==null){
        this.infoWindow = new AMap.InfoWindow({
          isCustom:true,
          closeWhenClickMap:true,
          offset:new AMap.Pixel((<number[]>this.offset)[0],(<number[]>this.offset)[1]),
          content: info.innerHTML  //使用默认信息窗体框样式，显示信息内容
        });
        this.infoWindow.on('close',()=>{
          this.infoWindow = null;
        });
        this.infoWindow.on('open',()=>{
          this.bindclick();
        });
        this.infoWindow.open(<AMapClass>this.map,new AMap.LngLat(d.lng,d.lat));
      }else{
        this.infoWindow.setContent(info.innerHTML);
        this.infoWindow.setPosition(new AMap.LngLat(d.lng,d.lat));
      }
    }
  }
});
</script>

<style scoped>
.map{
  width:100%;height:100%;
}
</style>
